package experiment_04_Pram;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class maxNumberClient {

	private static int[] array;

	public static void main(String[] args) {
		@SuppressWarnings("resource")
		Scanner input = new Scanner(System.in);
		// 生成数组
		System.out.println("请输入生成数组的长度：");
		int n = input.nextInt();
		array = getRandomArray(n);
		System.out.println(Arrays.toString(array));
		System.out.println("请输入线程个数：");
		int numberOfThread = input.nextInt();
		int[] a = new int[numberOfThread];
		try {
			List<Callable<Integer>> partitions = new ArrayList<Callable<Integer>>();
			int lenghtPerPartion = array.length / numberOfThread;
			for (int i = 0; i < numberOfThread; i++) {
				int lower = (i * lenghtPerPartion);
				int upper = (i == numberOfThread - 1) ? array.length - 1 : lower + lenghtPerPartion - 1;
				GetMaxNumber task = new GetMaxNumber(array, lower, upper);
				partitions.add(task);
			}
			// 创建固定大小为numberOfThread的线程池
			ExecutorService executorPool = Executors.newFixedThreadPool(numberOfThread);
			List<Future<Integer>> resultFromParts = executorPool.invokeAll(partitions, 10000, TimeUnit.SECONDS);
			executorPool.shutdown();// 执行完成之后关闭线程池
			for (int i = 0; i < resultFromParts.size(); i++) {
				a[i] = resultFromParts.get(i).get();
			}
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		}
		int max = a[0];
		for (int i = 1; i < a.length; i++) {
			if (max < a[i]) {
				max = a[i];
			}
		}
		System.out.println(max);
	}

	public static int[] getRandomArray(int lenght) {
		int[] array = new int[lenght];
		for (int i = 0; i < lenght; i++) {
			array[i] = (int) (Math.random() * 100) + 1;
		}
		return array;
	}

}
